# _*_ coding:utf-8 _*_
# @Time  : 2022.06.18
# @Author: zizlee
# 获取月份合约行情数据
import json
import time
import datetime

import pandas as pd
import requests
import urllib3
urllib3.disable_warnings()


# 进度打印
def print_progress_bar(current, total, color=35, title=''):  # percent是小数
    percent = round(current/total, 4)
    prefix_progress = '▓' * int(80 * percent)
    leave_progress = '▓' * (80 - int(80 * percent))
    # percent = '%.2f' % (percent * 100)
    print(f'\033[1;{color}m{current}/{total}\033[0m|\033[1;{color}m{prefix_progress}\033[0m{leave_progress} {title}')


def get_contract_quotes(start, end, variety, contract=''):
    url = 'https://210.13.218.130:9000/v1/quote/variety/daily/'
    query = {
        'start': start,
        'end': end,
        'variety': variety,
        'contract': contract
    }
    r = requests.get(url, params=query, verify=False)
    return r.json()['data']


def handler(indexes, start_date=None, end_date=None):
    total_count = len(indexes)
    if not start_date:
        start_date = datetime.datetime.today().strftime('%Y%m%d')
    if not end_date:
        end_date = datetime.datetime.today().strftime('%Y%m%d')
    for i, index_item in enumerate(indexes):
        value_key = index_item['value_key']
        quotes_data = get_contract_quotes(start=start_date, end=end_date, variety=index_item['variety_en'])
        quotes_data = list(filter(lambda x: x['contract'].endswith(index_item['contract_month']) and x['contract'].startswith(index_item['variety_en']), quotes_data))
        if len(quotes_data) < 1:
            print(f'无{index_item["name_zh"]}数据!')
            continue
        new_value_df = pd.DataFrame(quotes_data)[['quote_date', 'contract', value_key]]
        save_df = new_value_df.rename(columns={'quote_date': 'datadate', value_key: 'datavalue'})
        # print(index_item['source_id'], index_item['name_zh'])
        # 排序，去重，保留第一个
        save_df['c_month'] = save_df['contract'].apply(lambda x: x[-2:])
        save_df.sort_values(by=['datadate', 'contract'], inplace=True)
        save_df.drop_duplicates(subset=['datadate', 'c_month'], keep='first', inplace=True)
        del save_df['contract']
        del save_df['c_month']
        if save_df.empty:
            print(f'今日无{index_item["name_zh"]}数据!')
            continue
        save_data_to_server(index_item['id'], save_df.to_dict(orient='records'))
        msg = f'{index_item["name_zh"]} {index_item["source_id"]},起始日期:{start_date}保存完成.'
        print_progress_bar(current=i + 1, total=total_count, color=35, title=msg)
        time.sleep(0.5)


# 保存数据到指标中
def save_data_to_server(sheet_id, datalist):
    url = 'https://210.13.218.130:9000/v1/datalib/table/update/'
    body_data = {
        'dataid': sheet_id,
        'row_value': datalist
    }
    try:
        r = requests.post(url, json=body_data, verify=False)
        if r.json()['code'] != 200:
            raise ValueError(f'status_code={r.json()["code"]}')
    except Exception as e:
        if datalist:
            msg = f'保存数据指标 ID={sheet_id}失败了：{e}'
        else:
            msg = f'更新指标 ID={sheet_id} 刷新日期失败了：{e}'
        print(msg)
    else:
        pass


def main():
    with open('R_月份合约收盘价.json', encoding='utf8', mode='r') as fp:
        indexes = json.load(fp)
    print('读取指标数量:', len(indexes))
    if pointers:
        indexes = list(filter(lambda x: x['source_id'] in pointers, indexes))
    if exchange:
        indexes = list(filter(lambda x: x['ex_code'] == exchange, indexes))
    # indexes = list(filter(lambda x: 7412 <= x['id'] <= 7418, indexes))
    print('待更新指标数量:', len(indexes))
    handler(indexes, start_date=START_DATE, end_date=END_DATE)


if __name__ == '__main__':
    START_DATE = ''  # 20220102
    # END_DATE = datetime.datetime.today().strftime('%Y%m%d')
    END_DATE = ''
    # pointers = ['R00021407', 'R00021408', 'R00021409', 'R00021410', 'R00021411', 'R00021412']
    pointers = []
    exchange = ' '
    main()
